package com.test.ai.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.boot.jackson.JsonComponent;

/**
 * Created with IntelliJ IDEA.
 *
 * @description:
 * @author: liuziyang
 * @since: 2025/8/21 22:27
 * @modifiedBy:
 * @version: 1.0
 */
@JsonComponent
public class MessageDeserializer extends StdDeserializer<Message> {
  public MessageDeserializer() {
    super(Message.class);
  }

  @Override
  public Message deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
    JsonNode node = p.getCodec().readTree(p);
    String messageType = node.get("messageType").asText();
    String content = node.get("content").asText();

    return switch (messageType) {
      case "USER" -> new UserMessage(content);
      case "SYSTEM" -> new SystemMessage(content);
      case "ASSISTANT" -> new AssistantMessage(content);
      default -> throw new IllegalArgumentException("未知的消息类型: " + messageType);
    };
  }
}
